/* ***************************
* 电子表格操作界面JS
* @Editer wangjunfu
* ****************************/

$(function () {
    //名称修改后修改对应隐藏名称
    $("#query_name_input").change(function () {
        var newname = $(this).val();
        if (newname === "") {
            return showInfoAlert("电子表格名称不能为空！");
        }
        $("#sheetname").val(newname);
    });

    //拖拽到查询列处，这个不能共用，是独有的
    $("#fields_droppable").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function (event, ui) {
            var field_a = $(ui.draggable);
            var name = field_a.data("fname");
            var namecn = field_a.data("fnamecn");
            var type = field_a.data("ftype");
            var interval = field_a.data("datetype");
            if (type === 'filter') {
                return showInfoAlert("过滤条件类型列不能作为查询字段！");
            }
            var field = {};
            if (interval) {
                field.colName = name;
                var suffix = "";
                switch (interval) {
                    case "year":
                        suffix = "年份";
                        break;
                    case "month":
                        suffix = "月份";
                        break;
                    case "week":
                        suffix = "周";
                        break;
                }
                field.colNameCn = namecn + suffix;
                field.colType = type;
                field.interval = interval;
            } else {
                field.colName = name;
                field.colNameCn = namecn;
                field.colType = type;
            }
            //field.paramsField = [];   //undefined 的时候会过滤掉
            createQueryColumn(field);
        }
    });
});

/**
 * 打开查询列选择聚合条件
 * @param target
 */
function showFieldAggregates(target) {
    var jq_target = $(target);
    var jq_ul = jq_target.closest("li").find("ul");
    jq_ul.show();
}

/**
 * 移除查询字段
 * @param target
 */
function removeQueryField(target) {
    var li = $(target).closest("li[name=queryfield]");
    li.remove();
}

/**
 * 选择聚合函数
 * @param target
 * @param aggtype
 */
function chooseFieldAggregates(target, aggtype) {
    var li = $(target).closest("li[name=queryfield]");
    var agginput = li.find("input[name=queryagg]");
    var span = li.find("span[name=aggtype]");
    span.attr("class", "");
    var baseclass = "iconfont  dropdown-toggle icon-aggregate ";
    var type_class = "icon-null";
    switch (aggtype) {
        case "group":
            type_class = "icon-group";
            break;
        case "sum":
            type_class = "icon-sum";
            break;
        case "count":
            type_class = " icon-count";
            break;
        case "distinctcount":
            type_class = "icon-countd";
            break;
        case "min":
            type_class = "icon-min";
            break;
        case "max":
            type_class = "icon-max";
            break;
        case "avg":
            type_class = "icon-avg";
            break;
    }
    agginput.val(aggtype);
    span.attr("class", baseclass + " " + type_class);
}

/**
 * 创建查询列
 * @param field
 */
function createQueryColumn(field) {
    var jq_li = $('<li class="column-item column-measure" name="queryfield"  draggable="false">');
    var type_class = "number_ico_docu";
    switch (field.colType) {
        case "string":
            type_class = "string_ico_docu";
            break;
        case "numeric":
            type_class = "number_ico_docu";
            break;
        case "enum":
            break;
        case "text":
            break;
        case "date":
        case "time":
            type_class = "datetime_ico_docu";
            break;
    }
    var li_type = $('<span class="button ' + type_class + '"></span>');
    var li_agg = $('<span data-toggle="dropdown" name="aggtype" class="iconfont icon-null dropdown-toggle icon-aggregate"></span>');
    var li_field_name = field.colName;
    if (field.interval) {
        li_field_name = li_field_name + "(" + field.interval + ")";
    }
    var li_field = $('<span data-toggle="dropdown" class="data-item dropdown-toggle" style="width: 0px;" title="' + li_field_name + '" >' + li_field_name + '</span>');
    var li_showname = $('<span class="data-item" style="width: 160px;margin-left: 1px;" ><input class="query-input" name="querynames" value="' + field.colNameCn + '" type="text" style="margin-left: 3px;" /></span>');
    var li_close = $('<span class="iconfont icon-remove pull-right" onclick="removeQueryField(this)"></span>');
    var li_top = $('<span name="configParamSpan" style="font-size: 12px" class="iconfont icon-setup pull-right" onclick="configParams(this)"></span>');

    var li_ul = $('<ul class="kui-list aggregate-list  dropdown-menu" >\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'\')"><span class="iconfont icon-null"></span><span class="aggregate-text">无</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'group\')"><span class="iconfont icon-group"></span><span class="aggregate-text">分组</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'sum\')"><span class="iconfont icon-sum"></span><span class="aggregate-text">求和</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'min\')"><span class="iconfont icon-min"></span><span class="aggregate-text">最小值</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'max\')"><span class="iconfont icon-max"></span><span class="aggregate-text">最大值</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'avg\')"><span class="iconfont icon-avg"></span><span class="aggregate-text">平均值</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'count\')"><span class="iconfont icon-count"></span><span class="aggregate-text">计数</span></li>\n'
        + '             <li class="kui-list-item" onclick="chooseFieldAggregates(this,\'distinctcount\')"><span class="iconfont icon-countd"></span><span class="aggregate-text">计数(去重)</span></li>\n'
        + ' </ul>');

    var li_hide_fname = $("<input type='hidden' name='queryfields' value='" + field.colName + "'>");
    var li_hide_ftype = $("<input type='hidden' name='queryfieldtypes' value='" + field.colType + "'>");
    var li_hide_fagg = $("<input type='hidden' name='queryagg' value=''>");

    jq_li.append(li_type);
    jq_li.append(li_agg);
    jq_li.append(li_field);
    jq_li.append(li_showname);
    jq_li.append(li_close);
    jq_li.append(li_top);
    jq_li.append(li_ul);
    jq_li.append(li_hide_fname);
    jq_li.append(li_hide_ftype);
    jq_li.append(li_hide_fagg);

    if (field.interval) {
        var li_hide_interval = $("<input type='hidden' name='queryinterval' value='" + field.interval + "'>");
        jq_li.append(li_hide_interval);
    }

    var li_hide_paramsField = $("<input type='hidden' name='paramsField' value='" + field.paramsField + "'>");
    jq_li.append(li_hide_paramsField);

    $("#queryfields").append(jq_li);
}

/**
 * 删除过滤条件
 * @param target
 */
function removeFilter(target) {
    $(target).closest("li").remove();
}

function editFilterBefore(target) {
    //编辑过滤条件
    var pli = $(target).closest("li");
    var fn = pli.find("input[name=filterfield]").val();
    var fcn = pli.find("input[name=filterfieldcn]").val();
    var ft = pli.find("input[name=filterftypes]").val();
    var ftv = pli.find("input[name=textvalues]").val();
    var flt = pli.find("input[name=filtertype]").val();
    var ffromv, ftov;
    if (pli.find("input[name=fromvalues]").length > 0) {
        ffromv = pli.find("input[name=fromvalues]").val();
        ftov = pli.find("input[name=tovalues]").val();
    }
    editFilter(pli, fn, fcn, ft, flt, ftv, ffromv, ftov);
}

var current_eidt_filter_dom;
/**
 * 创建过滤器Dom
 * @param trme_str
 * @param fname
 * @param fnamecn
 * @param fieldtype
 * @param fvalue
 * @param ftype
 * @param fromvalue
 * @param tovalue
 */
function createFilterDom(trme_str, fname, fnamecn, fieldtype, fvalue, ftype, fromvalue, tovalue) {
    var filter_div = $("#filter_list_div");
    var f_li = $('<li class="level0" tabindex="0" hidefocus="true" treenode="" title="' + trme_str + '"> ');
    var f_li_a = $('<a class="level0 curSelectedNode" treenode_a="" style="width: calc(100% - 10px)">');
    var f_li_a_fi = $('<span  title="" treenode_ico="" class="fbutton" style=""><i class="fa fa-filter"></i></span>');
    var f_li_a_trme = $('<span  class="node_name" >' + trme_str + '</span>');
    var f_li_a_rm = $('<span title="移除过滤条件" treenode_ico="" class="fbutton pull-right" onclick="removeFilter(this)"><i class="fa fa-remove"></i></span>');
    var f_li_a_edit = $('<span treenode_ico="" class="fbutton pull-right" onclick="editFilterBefore(this)" ><i class="fa fa-edit"></i></span>');
    f_li_a.append(f_li_a_fi);
    f_li_a.append(f_li_a_trme);
    f_li_a.append(f_li_a_rm);
    f_li_a.append(f_li_a_edit);

    //提交input构建
    var input_fname = $('<input type="hidden" name="filterfield" value="' + fname + '" />');
    var input_fnamecn = $('<input type="hidden" name="filterfieldcn" value="' + fnamecn + '" />');
    var input_fieldtype = $('<input type="hidden" name="filterftypes" value="' + fieldtype + '" />');
    var input_fvalues = $('<input type="hidden" name="textvalues" value="' + fvalue + '" />');
    var input_ftype = $('<input type="hidden" name="filtertype" value="' + ftype + '" />');
    f_li.append(input_fname);
    f_li.append(input_fnamecn);
    f_li.append(input_fieldtype);
    f_li.append(input_fvalues);
    f_li.append(input_ftype);
    if (fromvalue) {
        var input_fromvalue = $('<input type="hidden" name="fromvalues" value="' + fromvalue + '" />');
        var input_tovalue = $('<input type="hidden" name="tovalues" value="' + tovalue + '" />');
        f_li.append(input_fromvalue);
        f_li.append(input_tovalue);
    }
    f_li.append(f_li_a);
    filter_div.append(f_li);
    if (current_eidt_filter_dom) {
        //编辑条件 移除后新增
        $(current_eidt_filter_dom).remove();
    }
}

/**
 * 编辑过滤器
 * @param fname
 * @param fieldtype
 * @param fvalue
 * @param ftype
 * @param fromvalue
 * @param tovalue
 */
function editFilter(target, fname, showname, fieldtype, ftype, fvalue, fromvalue, tovalue) {
    var f = {};
    f.colName = fname;
    f.colNameCn = showname;
    f.colType = fieldtype;
    current_eidt_filter_dom = target;

    switch (fieldtype) {
        case "string":
        case "enum":
            showStringFilterModal(f);
            if (ftype == "in" || ftype == "notIn") {    //in 和 notIn 条件
                $("#string_in_notin_select").val(ftype);
                $("#string_tab_in").tab("show");
                _string_term_type = "in";
                //还原值
                if (fvalue.indexOf(",") >= 0) {
                    var arr_v = fvalue.split(",");
                    $.each(arr_v, function (i, v) {
                        if (v != "") {
                            $("#field_choose_values_select").append("<option ondblclick=' dbClickAddOrRemove(this)' value='" + v + "'>" + v + "</option>");
                        }
                    });
                } else {
                    $("#field_choose_values_select").append("<option ondblclick=' dbClickAddOrRemove(this)' value='" + fvalue + "'>" + fvalue + "</option>");
                }
            } else if (ftype == "equal" || ftype == "notEqual") {   //等值条件
                $("#string_equal_notequal_select").val(ftype);
                _string_term_type = "equal";
                $("#string_tab_equal").tab("show");
                $("#stringEqualInput").val(fvalue);
            } else if (ftype == "like" || ftype == "notLike") {     //模糊匹配条件
                $("#string_like_notlike_select").val(ftype);
                _string_term_type = "like";
                $("#string_tab_like").tab("show");
                $("#stringLikeInput").val(fvalue);
            }
            break;
        case "date":
            var isAbsolute = true;          //是否绝对条件

            if (!fromvalue) {
                fromvalue = ""
            }
            if (!tovalue) {
                tovalue = ""
            }

            if (fvalue.indexOf("T") == 0 || fromvalue.indexOf("T") == 0 || tovalue.indexOf("T") == 0) {
                isAbsolute = false;
            }

            if (ftype == "range") {         //range 条件
                showDateFilterRange();
                if (isAbsolute) {
                    $("#absoluteStartDate").val(fromvalue);
                    $("#absoluteEndDate").val(tovalue);
                } else {
                    $("#relativeStartDate").val(fromvalue.replace("T", ""));
                    $("#relativeEndDate").val(tovalue.replace("T", ""));
                }
            } else if (ftype == "equal") {  //等值条件
                showDateFilterEqual();

                if (isAbsolute) {
                    $("#datepicker-autoclose").val(fvalue);
                } else {
                    $("#relativeStartDate").val(fvalue.replace("T", ""));
                }
            }

            if (isAbsolute) {
                showDateFilterAbsolute();
            } else {
                showDateFilterRelative();
            }

            showDateFilterModal(f);
            break;
        case "numeric":
            showNumberFilterModal(f);
            if (ftype == "range") {         //range 条件
                showNumberFilterRange();
                $("#numberFilterStartInput").val(fromvalue);
                $("#numberFilterEndInput").val(tovalue);
            } else if (ftype == "equal") {  //等值条件
                showNumberFilterEqual();
                $("#numberFilterInput").val(fvalue);
            }
            break;
    }
}

$(function () {
    //界面加载完成后检查是否编辑 如果sheetid存在 则立即运行
    var sheetid = $("#sheetid").val();
    if (sheetid) {
        execQuery();
    }
});

/**
 * 运行按钮
 */
function runExecQuery() {
    $("#currentpage").val(1);
    execQuery();
}

/**
 * 保存按钮
 */
function saveQuery() {
    showmodalmethod("数据正在保存中......");  //显示遮罩层

    ajax({
        url: "/analysis/spreadsheet/saveSheet",
        data: $("#queryform").serialize(),
        success: function (result) {
            if (result.returnCode === "1") {
                var sheetid = result.sheetid;
                $("#sheetid").val(sheetid);

                canclemodalmethod();    //取消遮罩层
                showInfoAlert("电子表格保存成功！", null);
            } else {
                canclemodalmethod();    //取消遮罩层
                showInfoAlert("电子表格保存失败！", null);
            }
        }
    });
}

/**
 * 预览按钮
 */
function previewQuery() {
    //查询预览必须先保存sheet，这样可以复用预览的代码
    var sheetid = $("#sheetid").val();

    if (sheetid === "") {
        showInfoAlert("请先保存电子表格再进行预览！", null);
        return;
    }

    window.open("/analysis/spreadsheet/preview?sheetid=" + sheetid);
}

/**
 * 执行查询
 */
function execQuery() {
    showmodalmethod(null);  //显示遮罩层

    var pagesize = Number($("#currentsize").val());
    var cpage = Number($("#currentpage").val());
    var limitsize = Number($("#limitsize").val());
    if (cpage * pagesize > limitsize) {
        $("#currentpage").val(limitsize / pagesize);
    }

    ajax({
        url: "/analysis/spreadsheet/execQuery",
        data: $("#queryform").serialize(),
        error: function (request) {
            canclemodalmethod();    //取消遮罩层
            showInfoAlert("服务器连接失败，请检查网络环境！", null);
        },
        success: function (result) {
            canclemodalmethod();    //取消遮罩层

            if (result.returnCode === "1") {
                //清空上次查询结果
                var datahead = $("#data_table_head");
                var databody = $("#data_table_body");
                datahead.empty();
                databody.empty();

                var page = result.page;
                //分页信息
                var end = page.start + page.pageSize;
                if (end > page.totalItems) {
                    end = page.totalItems;
                }

                $("#pagination-info").text("显示 " + page.start + " - " + end + " 共 " + page.totalItems + " 条记录");
                lastPage = page.totalPages;

                if (page.pn === 1) {
                    //当前页码为1时  第一页和上一页不可用
                    $("#queryFBtn").addClass("disabled");
                    $("#queryPBtn").addClass("disabled");
                } else {
                    $("#queryFBtn").removeClass("disabled");
                    $("#queryPBtn").removeClass("disabled");
                }

                if (page.pn === lastPage) {
                    //当前页码为最后一页时  最后一页和下一页不可用
                    $("#queryNBtn").addClass("disabled");
                    $("#queryLBtn").addClass("disabled");
                } else {
                    $("#queryNBtn").removeClass("disabled");
                    $("#queryLBtn").removeClass("disabled");
                }

                var rows = page.items;

                var startItem = 0;
                var lastItem = rows.length;

                //若多于20条则只显示20条
                if (rows.length > pagesize) {
                    startItem = page.start;
                    lastItem = end;
                }

                //数据信息
                if (rows.length > 0) {
                    for (var i = startItem; i < lastItem; i++) {
                        var row = rows[i];
                        if (startItem === i) {
                            //表头
                            datahead.append('<th style="min-width: 50px;width: 50px"></th>');
                            for (dthi in row.heads) {
                                var dth = row.heads[dthi];
                                datahead.append("<th nowrap='nowrap'>" + dth + "</th>");
                            }
                        }
                        //数据
                        var datatr = $("<tr>");
                        datatr.append('<td nowrap="nowrap" style="min-width: 50px;width: 50px;text-align: right">' + (i - startItem + 1) + '</td>');
                        for (dtdi in row.values) {
                            var dtd = row.values[dtdi];
                            datatr.append("<td nowrap='nowrap'>" + dtd + "</td>");
                        }
                        databody.append(datatr);
                    }
                } else {
                    showInfoAlert("没有查询到记录！", null);
                }
            } else {
                showInfoAlert(result.returnMessage, null);
            }
        }
    });
}

/**
 * 电子表格 分页函数
 */
var lastPage = 1;
function pageQuery(type) {
    var cpage = Number($("#currentpage").val());
    var tpage = 1;  //目标页
    switch (type) {
        case "f":   //第一页
            tpage = 1;
            break;
        case "p":   //上一页
            tpage = cpage - 1;
            if (tpage <= 0) {
                return showInfoAlert("没有上一页了！");
            }
            break;
        case "n":   //下一页
            tpage = cpage + 1;
            if (tpage > lastPage) {
                return showInfoAlert("没有下一页了！");
            }
            break;
        case "l":   //最后一页
            tpage = lastPage;
            break;
        case "j":   //跳转
            tpage = Number($("#jumpinput").val());
            if (tpage > lastPage || tpage <= 0 || tpage === "") {
                return showInfoAlert("错误的页数范围！页码范围[1~" + lastPage + "]");
            }
            break;
    }
    $("#currentpage").val(tpage);

    execQuery();
}

///=============== param start =========================
/**
 * 参数配置Tab 注意保存完毕以后是Json格式
 * Edit by wangjunfu
 */
var _crr_config_order_top_filed_li;

function configParams(target) {
    //定位当前所操作的字段
    _crr_config_order_top_filed_li = $(target).closest("li[name=queryfield]");

    var fieldName = _crr_config_order_top_filed_li.find("input[name=queryfields]").val();       //字段英文名称
    var fieldType = _crr_config_order_top_filed_li.find("input[name=queryfieldtypes]").val();   //字段类型
    var statisAgg = _crr_config_order_top_filed_li.find("input[name=queryagg]").val();  //统计类型
    var params = _crr_config_order_top_filed_li.find("input[name=paramsField]").val();  //配置参数

    $.ajax({
        url: "/analysis/spreadsheet/configparam",
        type: "POST",
        data: {fieldName: fieldName, fieldType: fieldType, statisAgg: statisAgg, params: params},
        async: false,
        error: function (request) {
            //error
        },
        success: function (data) {
            $('#config-param-modal').html(data);
            $("#config_params_modal").modal("show");
        }
    });
}

function setConfigParams() {
    $.ajax({
        url: "/analysis/spreadsheet/setconfigparam",
        type: "POST",
        data: $('#configParamForm').serializeArray(),
        async: false,
        error: function (request) {
            //error
        },
        success: function (data) {
            _crr_config_order_top_filed_li.find("input[name=paramsField]").val(data);
            $("#config_params_modal").modal("hide");
        }
    });
}

/**
 * 页面属性配置Tab 保存完毕以后是Json格式
 */
function pageParams() {
    var params = $("input[name='pageAttribute']").val();  //页面属性

    $.ajax({
        url: "/analysis/spreadsheet/pageparam",
        type: "POST",
        data: {params: params},
        async: false,
        error: function (request) {
            //error
        },
        success: function (data) {
            $('#page-param-modal').html(data);
            $("#page_params_modal").modal("show");
        }
    });
}

function setPageParams() {
    $.ajax({
        url: "/analysis/spreadsheet/setpageparam",
        type: "POST",
        data: $('#pageParamForm').serializeArray(),
        async: false,
        error: function (request) {
            //error
        },
        success: function (data) {
            var r = eval("(" + data + ")");
            $("#currentsize").val(r.pageSize);
            $("#limitsize").val(r.limitSize);

            $("input[name='pageAttribute']").val(data);
            $("#page_params_modal").modal("hide");
        }
    });
}

///=============== param end =========================
